# coding=utf-8

import urllib
import urllib2
import re
import os
import time
import sys

url_prefix = 'https://ting55.com/book/10994-'
url_postfix = ''

base_path = sys.path[0] + '/'

wait_time = 20

def getAudio(num):
    url = url_prefix + str(num) + url_postfix
    html = urllib.urlopen(url).read()

    first_text = '$(function(){var a={'
    first = html.index(first_text)
    last = html.index('"};ting55_play')
    print html[first+len(first_text):last]

    s = '{m4a:"(.+)"};ting55_play'
    pat = re.compile(s)

    list = pat.findall(html)
    if len(list) > 0:
        return list[0]
    else:
        return None
        # s = '{mp3:"(.+)"};ting55_play'
        # pat = re.compile(s)
        # list = pat.findall(html)
        #
        # if len(list) > 0:
        #     return list[0]
        # else:
        #     return None


def save(title, url):
    ext = '.m4a'
    if url.find('mp3') > -1:
        ext = '.mp3'
    local_file = base_path + title + ext
    try:
        urllib.urlretrieve(url, local_file)
        return True
    except:
        return False


def checkLast():
    big = 0
    for file in os.listdir(base_path):
        pos = file.rfind('.')
        num = file[0:pos]
        try:
            n = int(num)
            if n > big:
                big = n
        except:
            continue

    return big


def fetchLast():
    last = checkLast() + 1

    p = last
    for n in range(last, 731):
        print p
        url = getAudio(p)
        if url == None:
            print "can not get url"
            time.sleep(wait_time)
            continue
        print "before save --> number:"+str(p)+" url:"+url
        if save(str(n), url) == False:
            print "can not save file"
            time.sleep(wait_time)
            continue
        time.sleep(wait_time)
        print "after save"
        p += 1


def fetchLost():
    start = int(sys.argv[1])

    while True:
        if os.path.exists(str(start)+'.m4a') or os.path.exists(str(start)+'.mp3'):
            print "skip exists"
            start += 1
            continue

        url = getAudio(start)
        if url == None:
            print "can not get url"
            time.sleep(wait_time)
            continue
        print "before save --> number:" + str(start) + " url:" + url
        if save(str(start), url) == False:
            print "can not save file"
            time.sleep(wait_time)
            continue
        time.sleep(wait_time)
        print "after save"
        start += 1


if len(sys.argv) > 1:
    fetchLost()
else:
    fetchLast()
